package com.gitee.wsl.android.ext.okhttp

import android.net.Uri
import android.webkit.WebView
import com.gitee.wsl.android.ext.ApplicationInit.application
import com.gitee.wsl.android.ext.getDefaultUserAgentString
import com.gitee.wsl.android.ext.store.isContentUri
import com.gitee.wsl.android.file.readContent
import com.gitee.wsl.jvm.okhttp.OkHttpExt
import okhttp3.*
import timber.log.Timber
import java.io.File


val defaultUA: String by lazy {
    kotlin.runCatching {
        WebView(application).getDefaultUserAgentString()
    }.getOrElse {
        Timber.e("NetworkHelp , test")
        it.printStackTrace()
        "Mozilla/5.0 (Linux; Android 13; RMX3551 Build/SKQ1.220617.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/103.0.5060.129 Mobile Safari/537.36"
    }
}

val defaultCacheDir = File(application.cacheDir, "network_cache")


fun OkHttpClient.loadUri(data: Uri, callback:  (Result<String>) -> Unit){
    try {
        /*if (data == null) {
            callback(Result.success("load more ..."))
        } else*/ if (data.isContentUri) {
            data.readContent()?.let {
                callback(Result.success(it))
            }?:callback(Result.failure(RuntimeException("read $data content fail..")))
        } else {
            val request = OkHttpExt.get(data.toString())
            //callback(Result.success("get content for:$data"))
            newCall(request).execute().let {
                val md = it.body?.string() ?:return callback(Result.failure(RuntimeException("no body")))
                callback(Result.success(md))
            }

            /*newCall(request).enqueue(object : Callback {
               override fun onFailure(call: Call, e: java.io.IOException) {
                        callback(Result.failure(e))
                    }

                override fun onResponse(call: Call, response: Response) {
                        val md = response.body?.string() ?: ""
                        callback(Result.success(md))
                }
            })*/
        }
    } catch (t: Throwable) {
        Timber.d("loadUri catch ${t.message}")
        callback(Result.failure(t))
    }
}


